{#
 # ---------------------------------------------------------------------
 #
 # GLPI - Gestionnaire Libre de Parc Informatique
 #
 # http://glpi-project.org
 #
 # @copyright 2015-2024 Teclib' and contributors.
 # @copyright 2003-2014 by the INDEPNET Development Team.
 # @licence   https://www.gnu.org/licenses/gpl-3.0.html
 #
 # ---------------------------------------------------------------------
 #
 # LICENSE
 #
 # This file is part of GLPI.
 #
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
 #
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
 #
 # ---------------------------------------------------------------------
 #}

{% extends 'components/itilobject/timeline/form_timeline_item.html.twig' %}
{% import 'components/form/fields_macros.html.twig' as fields %}

{% set params = params|default({}) %}

{% block timeline_card %}
   {% if form_mode == 'view' %}
      {# Item displayed in timeline #}
      <div class="read-only-content w-100">
         {{ entry_i['content']|raw }}

         {% if entry_i['comment_submission']|length %}
            <div class='alert alert-info mt-2'>
                <div class='d-flex'>
                    <div><i class='ti ti-quote me-2'></i></div>
                    <div class="rich_text_container">
                        {{ entry_i['comment_submission']|enhanced_html({
                            'user_mentions': true,
                            'images_gallery': true
                        }) }}
                    </div>
                </div>
            </div>
         {% endif %}
         {% if entry_i['comment_validation']|length %}
            <div class='alert alert-info mt-2'>
                <div class='d-flex'>
                    <div><i class='ti ti-quote me-2'></i></div>
                    <div class="rich_text_container">
                        {{ entry_i['comment_validation']|enhanced_html({
                            'user_mentions': true,
                            'images_gallery': true
                        }) }}
                    </div>
                </div>
            </div>
         {% endif %}

         {% if entry_i['can_answer'] %}
            <hr class="my-2" />
            <form id="validationanswers_id_{{ entry_i['id'] }}"
                  action="{{ entry['type']|itemtype_form_path }}" method="post" data-submit-once>

               <input type="hidden" name="id" value="{{ entry_i['id'] }}" />
               <input type="hidden" name="users_id_validate" value="{{ entry_i['users_id_validate'] }}" />
               <input type="hidden" name="_glpi_csrf_token" value="{{ csrf_token() }}" />
               {{ call_plugin_hook('pre_item_form', {"item": subitem, 'options': params}) }}

               <div class="mb-3 comment-part">
                  {{ fields.textareaField(
                     'comment_validation',
                     '',
                     _n('Comment', 'Comments', 1),
                     {
                        'full_width': true,
                        'enable_richtext': true,
                        'is_horizontal': false,
                        'enable_fileupload': false,
                        'enable_mentions': true,
                        'entities_id': item.fields['entities_id'],
                        'rand': rand,
                     }
                  ) }}

                  {{ fields.fileField(
                      'filename',
                      null,
                      '',
                      {
                          'multiple': true,
                          'full_width': true,
                          'no_label': true,
                      }
                  ) }}
               </div>

               <div class="validation-footer">
                  <button type="submit" class="btn btn-outline-green" name="approval_action" value="approve">
                     <i class="fas fa-thumbs-up"></i>
                     <span class="validation-label">{{ __('Approve') }}</span>
                  </button>
                  <button type="submit" class="btn btn-outline-red" name="approval_action" value="refuse">
                     <i class="fas fa-thumbs-down"></i>
                     <span class="validation-label">{{ __('Refuse') }}</span>
                  </button>
               </div>
            </form>
         {% endif %}
      </div>
   {% elseif form_mode == 'answer' %}
      {# Form displayed when user updates its answer #}
      <form name="asset_form" style="width: 100%;" class="d-flex flex-column" method="post"
            action="{{ subitem.getFormURL() }}" enctype="multipart/form-data" data-track-changes="true" data-submit-once>

         <input type="hidden" name="id" value="{{ subitem.fields['id'] }}" />
         <input type="hidden" name="users_id_validate" value="{{ subitem.fields['users_id_validate'] }}" />
         <input type="hidden" name="_glpi_csrf_token" value="{{ csrf_token() }}" />

         {{ call_plugin_hook('pre_item_form', {"item": subitem, 'options': params}) }}

         <div class="mb-3 comment-part">
            {{ fields.textareaField(
               'comment_validation',
               subitem.fields['comment_validation'],
               _n('Comment', 'Comments', 1),
               {
                  'full_width': true,
                  'enable_richtext': true,
                  'is_horizontal': false,
                  'enable_fileupload': false,
                  'enable_mentions': true,
                  'entities_id': item.fields['entities_id'],
                  'rand': rand,
               }
            ) }}

            {{ fields.fileField(
                'filename',
                null,
                '',
                {
                    'multiple': true,
                    'full_width': true,
                    'no_label': true,
                }
            ) }}
         </div>

         <div class="validation-footer">
            <button type="submit" class="btn btn-outline-green" name="approval_action" value="approve">
               <i class="fas fa-thumbs-up"></i>
               <span class="validation-label">{{ __('Approve') }}</span>
            </button>
            <button type="submit" class="btn btn-outline-red" name="approval_action" value="refuse">
               <i class="fas fa-thumbs-down"></i>
               <span class="validation-label">{{ __('Refuse') }}</span>
            </button>
         </div>
      </form>
   {% else %}
      {# Form displayed when user creates/edits an approval request #}
      <div class="itilvalidation card mt-4">
         <form name="asset_form" style="width: 100%;" class="d-flex flex-column" method="post"
               action="{{ subitem.getFormURL() }}" enctype="multipart/form-data" data-track-changes="true" data-submit-once>
            <input type="hidden" name="itemtype" value="{{ item.getType() }}" />
            <input type="hidden" name="{{ item.getForeignKeyField() }}" value="{{ item.fields['id'] }}" />

            <div class="card-header">
                <h3 class="cart-title">{{ __("Validation request") }}</h3>
            </div>
            <div class="card-body">
               {{ fields.dropdownField(
                  'ITILValidationTemplate',
                  'itilvalidationtemplates_id',
                  '',
                  _n('Template', 'Templates', 1),
                  {
                     'full_width': true,
                     'on_change': 'itilvalidationtemplate_update' ~ rand ~ '(this.value);',
                     'entity': item.fields['entities_id'],
                     'rand': rand,
                  },
                ) }}

                {{ fields.readOnlyField(
                    'approval_requester',
                    get_current_user().getFriendlyName(),
                    _n('Requester', 'Requesters', 1),
                    {
                    'full_width': true,
                    'rand': rand,
                    }
                ) }}

                {% if subitem.isNewItem() %}
                    {% set validation_right = 'validate' %}
                    {% if item.getType() == 'Ticket' %}
                       {% if item.fields['type'] == constant('Ticket::INCIDENT_TYPE') %}
                          {% set validation_right = 'validate_incident' %}
                       {% elseif item.fields['type'] == constant('Ticket::DEMAND_TYPE') %}
                          {% set validation_right = 'validate_request' %}
                       {% endif %}
                    {% endif %}
                    {{ fields.field(
                        '_add_validation',
                        subitem.dropdownValidator({
                            'parents_id': item.fields['id'],
                            'entity': item.fields['entities_id'],
                            'itemtype_target': subitem.fields['itemtype_target'],
                            'items_id_target': subitem.fields['items_id_target'] ?? '',
                            'right': validation_right,
                            'display': false,
                            'rand': rand,
                        }),
                        __('Approver'),
                        {
                            'full_width': true,
                        }
                    ) }}
                {% else %}
                    {{ fields.readOnlyField(
                        '',
                        get_item_name(subitem.fields['itemtype_target'], subitem.fields['items_id_target']),
                        __('Approver'),
                        {
                           'full_width': true,
                        }
                    ) }}
                {% endif %}

                {{ fields.textareaField(
                    'comment_submission',
                    subitem.fields['comment_submission'],
                    _n('Comment', 'Comments', 1),
                    {
                    'full_width': true,
                    'enable_richtext': true,
                    'enable_fileupload': false,
                    'enable_mentions': true,
                    'entities_id': item.fields['entities_id'],
                    'rand': rand,
                    }
                ) }}

                {{ fields.fileField(
                    'filename',
                    null,
                    '',
                    {
                        'multiple': true,
                        'full_width': true,
                    }
                ) }}
            </div>

            {{ call_plugin_hook('post_item_form', {"item": subitem, 'options': params}) }}

            <div class="d-flex justify-content-center card-footer">
               {% if subitem.fields['id'] <= 0 %}
                  <button class="btn btn-primary me-2" type="submit" name="add">
                     <i class="fas fa-plus"></i>
                     <span>{{ _x('button', 'Add') }}</span>
                  </button>
               {% else %}
                  <input type="hidden" name="id" value="{{ subitem.fields['id'] }}" />
                  <button class="btn btn-primary me-2" type="submit" name="update">
                     <i class="far fa-save"></i>
                     <span>{{ _x('button', 'Save') }}</span>
                  </button>

                  {% if subitem.can(subitem.fields['id'], constant('PURGE')) %}
                     <button class="btn btn-outline-danger me-2" type="submit" name="purge"
                             onclick="return confirm('{{ __('Confirm the final deletion?') }}');">
                        <i class="fas fa-trash-alt"></i>
                        <span>{{ _x('button', 'Delete permanently') }}</span>
                     </button>
                  {% endif %}
               {% endif %}
            </div>

            <input type="hidden" name="_glpi_csrf_token" value="{{ csrf_token() }}" />
         </form>
      </div>

      {% if scroll %}
         <script type="text/javascript">
            window.scrollTo(0,document.body.scrollHeight);
         </script>
      {% endif %}

      <script type="text/javascript">
         function itilvalidationtemplate_update{{ rand }}(value) {
            $.ajax({
               url: '{{ path('/ajax/itilvalidation.php') }}',
               type: 'POST',
               data: {
                  validationtemplates_id: value,
                  items_id: '{{ item.fields['id'] }}',
                  itemtype: '{{ item.getType() }}'
               }
            }).done(function (data) {
               if (data.content !== undefined) {
                  // set textarea content
                  setRichTextEditorContent("comment_submission_{{ rand }}", data.content);
               }

               if (data.validatortype !== undefined) {
                  // set validator type
                  $("#dropdown__validatortype_{{ rand }}").trigger('setValue', "0");
                  $("#dropdown__validatortype_{{ rand }}").trigger('setValue', data.validatortype);

                  if (data.groups_id !== undefined && data.groups_id !== null) {
                     waitForElement("#dropdown_groups_id{{ rand }}").then((elm) => {
                        // set groups_id
                        $("#dropdown_groups_id{{ rand }}").ready(function() {
                           $("#dropdown_groups_id{{ rand }}").trigger('setValue', data.groups_id);
                        });

                        waitForElement("#dropdown_items_id_target{{ rand }}").then((elm) => {
                           // set items_id_target
                           $("#dropdown_items_id_target{{ rand }}").ready(function() {
                              $("#dropdown_items_id_target{{ rand }}").trigger('setValue', data.items_id_target);
                           });
                        });
                     });
                  } else if (data.items_id_target !== undefined) {
                     new Promise((resolve) => {
                        // if dropdown_items_id_target exists, wait for it to be removed
                        // is required because the dropdown is removed and recreated when the setValue is triggered
                        if ($("#dropdown_items_id_target{{ rand }}").length > 0) {
                           $("#dropdown_items_id_target{{ rand }}").on('remove', function() {
                              resolve();
                           });
                        } else {
                           resolve();
                        }
                     }).then(() => {
                        waitForElement("#dropdown_items_id_target{{ rand }}").then((elm) => {
                           // set items_id_target
                           $("#dropdown_items_id_target{{ rand }}").ready(function() {
                              $("#dropdown_items_id_target{{ rand }}").trigger('setValue', data.items_id_target);
                           });
                        });
                     });
                  }
               }
            });
         }
      </script>
   {% endif %}
{% endblock %}
